package com.sea.finance.controller;

import com.codecrane.core.util.DateUtils;
import com.codecrane.core.util.ExcelUtil;
import com.codecrane.core.web.Ajax;
import com.codecrane.core.web.AjaxReturn;
import com.codecrane.core.web.AjaxTableReturn;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sea.finance.entity.Inventory;
import com.sea.finance.mapper.InventoryMapper;
import com.sea.finance.service.InventoryService;
import com.sea.physical.entity.CreateDespatchSku;
import com.sea.physical.service.CreateDespatchSkuService;
import com.sea.product.service.ChannelService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;


/**
 *  控制器
 * @author 陈鸿飞
 *  <br/>
 *  <br/>
 */
@Controller
@RequestMapping("/sea/finance/inventory")
public class InventoryController {


    @Autowired
    private InventoryService inventoryService;
    @Autowired
    private ChannelService channelService;
    @Autowired
    private CreateDespatchSkuService createDespatchSkuService;
    @Autowired
    private InventoryMapper inventoryMapper;

    public static void main(String[] args) {

    }

    /**
     * 管理主页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/main")
    public String main(Model model) {
        model.addAttribute("channel", channelService.findByCnd(null));
        return "/sea/finance/inventory/main";
    }
    @RequestMapping("/cost")
    public String cost(Model model) {

        return "/sea/finance/inventory/cost";
    }

    @RequestMapping(value = "/chf")
    public String test(){
        List<Inventory> byCnd = inventoryService.findByCnd(null);
        for(Inventory inventory:byCnd){
            CreateDespatchSku byMonthChannelSku = createDespatchSkuService.findByMonthChannelSku(inventory.getInventoryDate(), inventory.getInventoryChannelName(), inventory.getInventorySku());
            if(null !=byMonthChannelSku){
                inventory.setErpProduceUnitPrice(byMonthChannelSku.getErpProduceUnitPrice());
                inventory.setInventoryBorrowPrice(byMonthChannelSku.getErpProduceUnitPrice()+byMonthChannelSku.getCreateCustomTax()+byMonthChannelSku.getCreateCustomFreight());
                inventory.setInventoryBorrowMoney(inventory.getInventoryBorrowNumber() * inventory.getInventoryBorrowPrice());
                inventory.setCreateCustomFreight(byMonthChannelSku.getCreateCustomFreight());
                inventory.setCreateCustomTax(byMonthChannelSku.getCreateCustomTax());
                inventoryMapper.updateBorrowPrice(inventory);
            }
        }
        return "";
    }

    /**
     * 新增主页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/addPage")
    public String addPage(Model model) {

        return "/sea/finance/rate/add";
    }

    /**
     * 新增主页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/editPage")
    public String editPage(Model model, @RequestParam("id") Integer id) {
        return "/sea/finance/rate/edit";
    }

    @ResponseBody
    @RequestMapping("/findByCost")
    public AjaxTableReturn findByCost(@RequestParam(value = "limit", defaultValue = "10") int pagesize,
                                     @RequestParam(value = "offset", defaultValue = "0") int start,
                                     Inventory inventory) {
        start = start > 0 ? start / pagesize + 1 : 1;
        PageHelper.startPage(start, pagesize);
        List<Inventory> list = inventoryService.findSkuCost(inventory);
        PageInfo<Inventory> page = new PageInfo<>(list);
        return Ajax.tableDataOk(page.getTotal(), page.getList());
    }

    /**
     * 分页条件查询
     *
     * @param pagesize
     * @param start
     * @return
     */
    @ResponseBody
    @RequestMapping("/findByCnd")
    public AjaxTableReturn findByCnd(@RequestParam(value = "limit", defaultValue = "10") int pagesize,
                                     @RequestParam(value = "offset", defaultValue = "0") int start,
                                     Inventory inventory) {
        start = start > 0 ? start / pagesize + 1 : 1;
        PageHelper.startPage(start, pagesize);
        List<Inventory> list = inventoryService.findByCnd(inventory);
        PageInfo<Inventory> page = new PageInfo<>(list);
        return Ajax.tableDataOk(page.getTotal(), page.getList
                ());
    }

    @ResponseBody
    @RequestMapping("/test")
    public AjaxReturn test(@RequestParam("testDate") String testDate) {
        AjaxReturn result = Ajax.fail().setMsg("保存失败！");
        try {
            inventoryService.inventory(testDate);
            //inventoryService.updateChange(testDate);
            result.setOk(true).setMsg("保存成功！");

        } catch (DuplicateKeyException e) {
            result.setMsg(testDate+"数据已存在！");
            return result;
        } catch (RuntimeException e) {
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }


    /**
     * 导出收货数据
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/exportSkuCost")
    @ResponseBody
    public void exportSkuCost(HttpServletRequest request, HttpServletResponse response, Inventory inventory) {
        List<Inventory> list = inventoryService.findSkuCost(inventory);
        String[] title = {"渠道","SKU","商品名称","不含税单价","预估关税","预估运费"};
        String fileName = "SKU成本表" + DateUtils.dateToString(new Date(),"yyyyMMdd") + ".xls";
        String sheetName = "SKU成本表";
        String[][] content = new String[list.size()][6];
        for (int i = 0; i < list.size(); i++) {
            content[i] = new String[title.length];
            Inventory obj = list.get(i);
            content[i][0] = obj.getInventoryChannelName();
            content[i][1] = obj.getInventorySku();
            content[i][2] = obj.getProductName();
            content[i][3] = obj.getErpProduceUnitPrice()+"";
            content[i][4] = obj.getCreateCustomTax()+"";
            content[i][5] = obj.getCreateCustomFreight()+"";
        }
        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 导出收货数据
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/export")
    @ResponseBody
    public void export(HttpServletRequest request, HttpServletResponse response, Inventory inventory) {
        List<Inventory> list = inventoryService.findByCnd(inventory);
        String[] title = {"时间","SKU","渠道",
                          "期初数量","调配数量","期初单价","期初金额","期初不含税单价","期初关税","期初运费",
                          "借方发生数量","入库单价","不含税单价","预估关税","预估运费","借方发生金额",
                          "贷方发生数量","出库单价","贷方发生金额",
                          "期末余额数量","结存单价","期末余额金额","期末不含税单价","期末关税","期末运费"};
        String fileName = "进销存表" + DateUtils.dateToString(new Date(),"yyyyMMdd") + ".xls";
        String sheetName = "进销存表";
        String[][] content = new String[list.size()][25];
        for (int i = 0; i < list.size(); i++) {
            content[i] = new String[title.length];
            Inventory obj = list.get(i);
            content[i][0] = obj.getInventoryDate();
            content[i][1] = obj.getInventorySku();
            content[i][2] = obj.getInventoryChannelName();
            content[i][3] = obj.getInventoryBeginNumber()+"";
            content[i][4] = (null==obj.getInventoryChange()?0:obj.getInventoryChange())+"";
            content[i][5] = obj.getInventoryBeginPrice()+"";
            content[i][6] = obj.getInventoryBeginMoney()+"";
            content[i][7] = obj.getInventoryBeginUnitPrice()+"";
            content[i][8] = obj.getInventoryBeginCustomTax()+"";
            content[i][9] = obj.getInventoryBeginCustomFreight()+"";
            content[i][10] = obj.getInventoryBorrowNumber()+"";
            content[i][11] = obj.getInventoryBorrowPrice()+"";
            content[i][12] = obj.getErpProduceUnitPrice()+"";
            content[i][13] = obj.getCreateCustomTax()+"";
            content[i][14] = obj.getCreateCustomFreight()+"";
            content[i][15] = obj.getInventoryBorrowMoney()+"";
            content[i][16] = obj.getInventoryCreditNumber()+"";
            content[i][17] = obj.getInventoryCreditPrice()+"";
            content[i][18] = obj.getInventoryCreditMoney()+"";
            content[i][19] = obj.getInventoryEndNumber()+"";
            content[i][20] = obj.getInventoryEndPrice()+"";
            content[i][21] = obj.getInventoryEndMoney()+"";
            content[i][22] = obj.getInventoryEndUnitPrice()+"";
            content[i][23] = obj.getInventoryEndCustomTax()+"";
            content[i][24] = obj.getInventoryEndCustomFreight()+"";
        }
        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(),"ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
